﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using IbatisNetDemo.Models;
using IbatisNetDemo.Common;
using IBatisNet.Common.Logging;
using Newtonsoft.Json;
using System.IO;
using System.Collections;
using Newtonsoft.Json.Converters;

namespace IbatisNetDemo.Controllers
{
    public class HomeController : Controller
    {

        ILog logger = LogManager.GetLogger(typeof(HomeController));
        public ActionResult Index()
        {
            return View("Index");
        }

        public string List()
        {
            IList<User> users = BaseDA.QueryForList<User>("SelectAllUser", new User());
            IsoDateTimeConverter idtc = new IsoDateTimeConverter();
            idtc.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
            return JsonConvert.SerializeObject(users, idtc);
        }

        public string Delete()
        {
            StreamReader sr = new StreamReader(Request.InputStream);
            string inputStr = sr.ReadToEnd();
            Hashtable ht = new Hashtable();
            int[] ids = JsonConvert.DeserializeObject<int[]>(inputStr);
            int i = BaseDA.Delete("DeleteUserByIdList", ids);
            if (i > 0)
            {
                ht["msg"] = "删除成功";
            }
            else
            {
                ht["msg"] = "删除失败";
            }
            ht["success"] = i > 0;
            return JsonConvert.SerializeObject(ht);
        }

        public string Add()
        {
            StreamReader sr = new StreamReader(Request.InputStream);
            User user = JsonConvert.DeserializeObject<User>(sr.ReadToEnd());
            Hashtable ht = new Hashtable();
            int i = 0;
            if (user.id == 0)
            {
                user.regist_date = DateTime.Now;
                user.last_login_date = DateTime.Now;
                i = BaseDA.Insert<User>("InsertUser", user);
                ht["msg"] = i > 0 ? "新增成功" : "新增失败";
            }
            else
            {
                i = BaseDA.Update<User>("UpdateUser", user);

                ht["msg"] = i > 0 ? "修改成功" : "修改失败";
            }
            ht["success"] = i > 0;
            return JsonConvert.SerializeObject(ht);
        }

    }
}
